{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DeepLearning - Transfer Learning\n",
    "\n",
    "Classify automobile vs airplane using DNN featurization and transfer learning\n",
    "against a subset of images from CIFAR-10 dataset."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Load DNN Model and pick one of the inner layers as feature output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from synapse.ml.cntk import CNTKModel\n",
    "from synapse.ml.downloader import ModelDownloader\n",
    "import numpy as np, os, urllib, tarfile, pickle, array\n",
    "from os.path import abspath\n",
    "from pyspark.sql.functions import col, udf\n",
    "from pyspark.sql.types import *\n",
    "\n",
    "from pyspark.sql import SparkSession\n",
    "\n",
    "# Bootstrap Spark Session\n",
    "spark = SparkSession.builder.getOrCreate()\n",
    "\n",
    "from synapse.ml.core.platform import running_on_synapse, running_on_databricks\n",
    "\n",
    "modelName = \"ConvNet\"\n",
    "if running_on_synapse():\n",
    "    modelDir = \"abfss://synapse@mmlsparkeuap.dfs.core.windows.net/models/\"\n",
    "elif running_on_databricks():\n",
    "    modelDir = \"dbfs:/models/\"\n",
    "else:\n",
    "    modelDir = \"/tmp/models/\"\n",
    "\n",
    "d = ModelDownloader(spark, modelDir)\n",
    "model = d.downloadByName(modelName)\n",
    "print(model.layerNames)\n",
    "cntkModel = (\n",
    "    CNTKModel()\n",
    "    .setInputCol(\"images\")\n",
    "    .setOutputCol(\"features\")\n",
    "    .setModelLocation(model.uri)\n",
    "    .setOutputNode(\"l8\")\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Format raw CIFAR data into correct shape."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "imagesWithLabels = spark.read.parquet(\n",
    "    \"wasbs://publicwasb@mmlspark.blob.core.windows.net/CIFAR10_test.parquet\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Select airplanes (label=0) and automobiles (label=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "imagesWithLabels = imagesWithLabels.filter(\"labels<2\")\n",
    "imagesWithLabels.cache()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Featurize images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "featurizedImages = cntkModel.transform(imagesWithLabels).select([\"features\", \"labels\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use featurized images to train a classifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from synapse.ml.train import TrainClassifier\n",
    "from pyspark.ml.classification import RandomForestClassifier\n",
    "\n",
    "train, test = featurizedImages.randomSplit([0.75, 0.25])\n",
    "\n",
    "model = TrainClassifier(model=RandomForestClassifier(), labelCol=\"labels\").fit(train)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Evaluate the accuracy of the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from synapse.ml.train import ComputeModelStatistics\n",
    "\n",
    "predictions = model.transform(test)\n",
    "metrics = ComputeModelStatistics(evaluationMetric=\"accuracy\").transform(predictions)\n",
    "metrics.show()"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
